﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using System.Threading;

namespace Dice
{
    public partial class Form1 : Form
    {
        //开始或是停止的标识
        private bool flg = false;

        private Thread th;

        public Form1()
        {
            InitializeComponent();
        }

        private void Form1_Load(object sender, EventArgs e)
        {
            //取消跨线程错误检测
            Control.CheckForIllegalCrossThreadCalls = false;
        }

        private void Form1_FormClosing(object sender, FormClosingEventArgs e)
        {
            //当关闭窗体时，把后台线程也关闭
            if (this != null)
            {
                th.Abort();
            }
        }

        private void PlayGame()
        {
            Random r = new Random();
            while(flg==true)
            {
                lblDice1.Text = r.Next(1, 7).ToString();
                lblDice2.Text = r.Next(1, 7).ToString();
                lblDice3.Text = r.Next(1, 7).ToString();
            }
        }

        private void button1_Click(object sender, EventArgs e)
        {
            if (flg)
            {
                flg = true;
                button1.Text = "停止";
                //线程调用playgame方法
                th = new Thread(PlayGame);
                //后台运行
                th.IsBackground = true;
                th.Name = "丢色子";
                th.Start();
            }
            else
            {
                flg = false;
                button1.Text = "开始";
            }
        }
    }
}
